local M = {}
local s = require('utils.misc')
local fnamemodify = vim.fn.fnamemodify

---@param path string
---@return table
M.read_json_file = function(path)
    local file, _ = io.open(path, "r")
    local content = file:read("*a") -- Read the entire content
    file:close()

    return vim.fn.json_decode(content) or {}
end

M.file_exists = function(name)
    local f = io.open(name, "r")
    return f ~= nil and io.close(f)
end

M.split_file_name = function(name,blank_width)
    local strings = require('plenary.strings')
    local filename = name:match("([^/]+)$")
    local path = name:match("(.+)/[^/]+$")
    local path2 = fnamemodify(path, ":h:t") .. "/" .. fnamemodify(path, ":t")

    local w = strings.strdisplaywidth(filename)+strings.strdisplaywidth(path2)
    local s = string.rep(' ',blank_width-1-w)

    return filename .. s .. path2 .. '/'
end

M.split_file_name_2 = function(name, blank_width)
    -- add parent path (tail part) before the filename
    local strings = require('plenary.strings')
    local filename = name:match("([^/]+)$")
    local path = name:match("(.+)/[^/]+$")
    local parent = fnamemodify(path, ":h:t")

    local new_path = fnamemodify(path, ":t")
    if new_path == 'v:null' then
        -- file out of current working directory
        return nil,nil,nil,nil
    end

    local new_filename = new_path .. "/" .. filename

    local w = strings.strdisplaywidth(new_filename)+strings.strdisplaywidth(parent)
    local s = string.rep(' ',blank_width-1-w)

    -- Return the formatted string and position info for highlighting
    local result = new_filename .. s .. parent .. '/'
    local parent_end_pos = #new_path
    local parent_end_pos2 = strings.strdisplaywidth(result) - strings.strdisplaywidth(parent)

    return result, parent_end_pos, parent_end_pos2, strings.strdisplaywidth(parent)
end

return M
-- EOP
